package org.elucid.chess.piece;

import java.util.ArrayList;
import java.util.List;

import org.elucid.chess.model.Board.Direction;
import org.elucid.chess.model.Game;
import org.elucid.chess.model.Move;
import org.elucid.chess.model.Piece;
import org.elucid.chess.model.Square;

/**
 * 
 * @author george
 *
 */
public class Pawn extends Piece {

	/**
	 * 
	 * @param isWhite
	 */
    public Pawn(boolean isWhite) {
        super(isWhite);
    }

    @Override
    public List<Move> listLegalMoves(Game game, boolean isOnlyThreats) {
        List<Move> legalMoves = new ArrayList<Move>();
        
        Square fromSquare = game.getPieceSquares().get(this);
        
        // check forward movements
        Direction direction = isWhite ? Direction.North : Direction.South;
        int max_distance = this.moveHistory.size() > 0 ? 1 : 2;
        for( int distance = 1; !isOnlyThreats && distance <= max_distance; distance++ )
        {
            Square toSquare = game.getBoard().getSquareAt(fromSquare, direction, distance);
            if( toSquare != null )
            {
	            Piece pieceAtSquare = game.getPieceSquares().getKey(toSquare);
	            if( pieceAtSquare==null )
	                legalMoves.add( new Move(fromSquare, toSquare, false) );
	            else 
	            	break; // don't continue to distance=2 if blocked inbetween
            }
        }
        
        // now check for captures
        Direction aheadLeftDirection = isWhite ? Direction.NorthEast : Direction.SouthWest;
        Square aheadLeftSquare = game.getBoard().getSquareAt(fromSquare, aheadLeftDirection, 1);
        if (aheadLeftSquare != null) {
			Piece piece = game.getPieceSquares().getKey(aheadLeftSquare);
			Move move = new Move(fromSquare, aheadLeftSquare, true );
			if( isOnlyThreats )
			{
				// when calculating threats, destination may be empty
				legalMoves.add(move);
			}
			else
			{	// a piece must be in destination for this move to occur
				if (piece != null && (!(piece instanceof King) &&  isOpponentsPiece(piece) ))
				{
					legalMoves.add(move);
				}
			}
    	}
        
        Direction aheadRightDirection = isWhite ? Direction.NorthWest : Direction.SouthEast;
        Square aheadRightSquare = game.getBoard().getSquareAt(fromSquare, aheadRightDirection, 1);
        if (aheadRightSquare != null) {
			Piece piece = game.getPieceSquares().getKey(aheadRightSquare);
			Move move = new Move(fromSquare, aheadRightSquare, true );
			if( isOnlyThreats )
			{
				// when calculating threats, destination may be empty
				legalMoves.add(move);
			}
			else
			{
				// a piece must be in destination for this move to occur
				if (piece != null && (!(piece instanceof King) &&  isOpponentsPiece(piece) ))
				{
					legalMoves.add(move);
				}
			}
    	}
       
        return legalMoves;
    }
}
